package com.xhwl.centiotdata.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.weigh.WeighIntegrationFactory;
import com.xhwl.centiotdata.handler.weigh.WeighIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.weigh.WeighConfigDTO;
import com.xhwl.centiotdata.service.IWeighService;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.service.integrateconfig.WeighIntegrationConfig;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.iotdata.mettler.WeighDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.query.cent.device.DeviceQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author pengjunming
 * @description
 * @date 2022/10/11 17:54
 */
@Service
@Slf4j
public class WeighServiceImpl implements IWeighService {

    @Resource
    private IDeviceCentService iDeviceCentService;

    @Resource
    private WeighIntegrationConfig weighIntegrationConfig;


    @Override
    public ResultJson weigh(WeighDTO dto) {

        DeviceQuery deviceQuery = new DeviceQuery();
        deviceQuery.setCategoryIdList(Collections.singletonList(CategoryEnum.WEIGHBRIDGE_SYSTEM.getId()));
        deviceQuery.setProjectId(dto.getProjectId());
        Map<Integer, Object> result = new HashMap<>();
        try {
            //获取设备信息
            List<DeviceDTO> list = iDeviceCentService.list(null, deviceQuery);
            if (!CollectionUtils.isEmpty(list)) {
                DeviceDTO deviceDTO = list.get(0);
                Integer productId = deviceDTO.getProductId();
                WeighIntegrationHandler handler = WeighIntegrationFactory.getInvokeStrategy(productId);
                if (Objects.nonNull(handler)) {
                    // 获取地磅配置
                    List<WeighConfigDTO> configIntegrationConfig = weighIntegrationConfig.getIntegrationConfig(dto.getProjectId());
                    configIntegrationConfig.forEach(config -> {
                        JSONObject weigh = handler.weigh(config, dto);
                        result.put(dto.getProjectId(), weigh);
                    });
                }
                return ResultJson.successWithResult(result);
            } else {
                return ResultJson.fail("设备不存在");
            }
        } catch (Exception e) {
            log.error("称重异常", e);
            return ResultJson.fail("称重失败");
        }
    }
}
